package source.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import source.entity.Config;
import source.repo.Generator;
import source.repo.Result;

import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RequestMapping("/")
@RestController
public class configController {

    @Autowired
    Config config;

    @Autowired
    DruidDataSource dataSource;

    @PostMapping("/setCfg")
    public Result setConfig(@RequestBody Config cfg , @Qualifier Generator generator){
        config=cfg;
        System.out.println(cfg);
        config.setModule_name_sub(String.valueOf(config.getModule_name().split("-")[1].toCharArray()));
        config.setPackage_dir_dis(config.getPackage_dir().replaceAll("\\.","/"));
        generator.startGenerate(config);
        return Result.success(config);
    }

    @GetMapping("/getCfg")
    public Result getConfig() throws SQLException {
        DruidPooledConnection connection = dataSource.getConnection();
        ResultSet rs = connection.prepareStatement("show tables").executeQuery();
        ArrayList<String> list = new ArrayList<>();
        while (rs.next()) {
            list.add(rs.getString(1));
        }
        rs.close();
        connection.close();
        JSONObject json = new JSONObject();
        config.tables= list;
        json.put("config",config);
        return Result.success(json);
    }

    // truncate cms_help;  ALTER TABLE cms_help  AUTO_INCREMENT = 1;
    @PostMapping("/insert")
    public Result insert(@RequestBody List<JSONObject> list,@RequestParam("table") String table  ) throws SQLException {
        String head = "insert into -(".replaceAll("-",table);

        List<String> sqls = list.stream().map(e -> {
            String str = head;
            String collect0 = e.entrySet().stream().map(elek -> {
                return "`" + elek.getKey().replaceAll("[A-Z]", "_$0").toLowerCase().toString() + "`";
            }).collect(Collectors.joining(","));

            String sql_sub0 = str +collect0+")";

            String collect1 = e.entrySet().stream().map(ele -> {
                return "'" + ele.getValue().toString() + "'";
            }).collect(Collectors.joining(","));
            String sql_sub1 = sql_sub0+ " values("+collect1 + ");";
            return sql_sub1;
        }).collect(Collectors.toList());
        DruidPooledConnection connection = dataSource.getConnection();

        Statement statement = connection.createStatement();

        sqls.stream().forEach(e->{
            try {
                statement.addBatch(e);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        });

        int[] ints = statement.executeBatch();

        connection.close();
        statement.close();
        return Result.success(ints);
    }




    @GetMapping("/dir")
    public Result getDir() throws FileNotFoundException {
        String projectPath = config.getProjectPath();
        String[] list = new File(projectPath).list();
        List<String> strings = Arrays.stream(list).filter(v -> {
            if (v.contains(".")) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        return Result.success(strings);
    }

    @GetMapping("/entity/dir")
    public Result entityDir(@RequestParam String moduleName, @RequestParam String pack) throws FileNotFoundException {
        String projectPath = config.getProjectPath();
        String basepath = projectPath  + moduleName + config.getSrc()+config.getPackage_dir() + "/entity/";
        File file = new File(basepath);
        System.out.println(projectPath  + moduleName + config.getSrc()+config.getPackage_dir() + "/entity/");
        if(file.exists()){
            String[] list = file.list();
            List<String> collect = Arrays.stream(list).map(v -> {
                return v.split("\\.")[0];
            }).collect(Collectors.toList());
            return Result.success(collect);
        }else {
            return Result.success("不存在的路径");
        }

    }



    @GetMapping("/entity")
    public Result entity(@RequestParam String moduleName, @RequestParam String pack, @RequestParam String className) throws FileNotFoundException {
        String projectPath = config.getProjectPath();
        String basepath = projectPath  + moduleName + config.getSrc()+config.getPackage_dir() + "/entity/" + className +".java";
        File file = new File(basepath);
        System.out.println(basepath);
        if(file.exists()){
            JSONObject entity = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            File file1 = new File(basepath);
            try {
                BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
                List<String> strings = buffer.lines().collect(Collectors.toList());
                String code = "".join("", strings);
                Matcher matcher = Pattern.compile("private\\s*([a-z|A-Z|0-9|_]*)\\s*([a-z|A-Z|0-9|_]*);").matcher(code);
                while (matcher.find()){
                    String mock = null;
                    switch (matcher.group(1)){
                        case "String": {
                            if (matcher.group(2).contains("phone")) {
                                mock = "/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/";
                            }else if(matcher.group(2).contains("email")) {
                                mock = "@email";
                            }else if(matcher.group(2).contains("name")) {
                                mock = "@cname";
                            }else if(matcher.group(2).contains("password")) {
                                mock = "123456";
                            }else {
                                mock = "@csentence";
                            }
                        };break;
                        case "Integer": mock = "@natural(100,99999)"  ;break;
                        case "Boolean": mock = "@boolean"  ;break;
                        case "Long":  {
                            if (matcher.group(2).contains("id")) {
                                mock = null;
                            }else {
                                mock = "@natural(999999,100000000)";
                            }
                        };break;
                        default:break;
                    }
                    entity.put(matcher.group(2),mock);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            jsonObject.put("entity",entity);
            return Result.success(jsonObject);
        }else {
            return Result.success("不存在的路径");
        }

    }


}
